import type {TreeDataItem} from "ant-design-vue/es/tree";
import type {SysUserReq} from "#/type/user";
import type {Reactive, Ref} from "vue";
import {getDeptAndChildesByIdApi} from "#/api/core/dept";
import {onBeforeMount, reactive, ref,watch} from "vue";

export default function (
    fetchTableData: Function,
    treeExpandedKeys: Reactive<(string | number)[]>,
    treeSelectedKeys: Ref<(string | number)[]>,
    formSearch: Reactive<SysUserReq>,
    tablePagination: Reactive<any>
) {
  // tree节点搜索
  const treeSearchValue = ref<string>('');
  // tree 数据
  let treeData = reactive<TreeDataItem[]>([]);
  let defaultTreeData = reactive<TreeDataItem[]>([]);
  const fetchTreeData = () => {
    getDeptAndChildesByIdApi().then(res => {
      const arr2tree = array2Tree(res);
      Object.assign(treeData, arr2tree);
      defaultTreeData.splice(0, defaultTreeData.length, ...arr2tree);
    })
  }
    const onTreeExpand = (keys: (string | number)[], e: { expanded: boolean, node: TreeDataItem }) => {
        let mergedKeys = [...new Set([...treeExpandedKeys])];
        if (mergedKeys.indexOf(e.node.key) === -1) {
            // 合并 + 去重
            mergedKeys = [...new Set([...keys, ...treeExpandedKeys, e.node.key])];
            // 清空并替换为 mergedKeys
            treeExpandedKeys.splice(0, treeExpandedKeys.length, ...mergedKeys);
        } else {
            mergedKeys = mergedKeys.filter(item => item !== e.node.key);
            treeExpandedKeys.splice(0, treeExpandedKeys.length, ...mergedKeys);
        }
    };

    const onTreeSelect = (keys: (string | number)[], e: { selected: boolean, node: TreeDataItem, }) => {
        treeSelectedKeys.value = keys;
        let mergedKeys = [...new Set([...treeExpandedKeys])];
        if (mergedKeys.indexOf(e.node.key) === -1) {
            // 合并 + 去重
            mergedKeys = [...new Set([...keys, ...treeExpandedKeys, e.node.key])];
            // 清空并替换为 mergedKeys
            treeExpandedKeys.splice(0, treeExpandedKeys.length, ...mergedKeys);
        } else {
            mergedKeys = mergedKeys.filter(item => item !== e.node.key);
            treeExpandedKeys.splice(0, treeExpandedKeys.length, ...mergedKeys);
        }
        const dept_id = (treeSelectedKeys.value || [] as (string | number)[]).join(',')
        let params: SysUserReq = {...tablePagination, ...formSearch, dept_id}
        fetchTableData(params)
    };

  onBeforeMount(() => {
    fetchTreeData()
  })
  // 监听搜索框变化
  watch(treeSearchValue, value => {
    if (value) {
      let filterTreeData = filterTreeWithParents(treeData, value);
      treeData.splice(0, treeData.length, ...filterTreeData);
    } else {
      treeData.splice(0, treeData.length, ...defaultTreeData);
    }
  });

  function array2Tree(arr: any[]) {
    const nodes: Record<number, any> = {};     // ID -> 节点映射
    const roots: TreeDataItem[] = [];   // 根节点集合
    // 初始化所有节点
    arr.forEach(item => {
      nodes[item.dept_id] = {
        "title": item.dept_name,
        "key": item.dept_id,
        "children": []
      };
    });
    arr.forEach(item => {
      const node = nodes[item.dept_id];
      const parent = nodes[item.parent_id];
      parent ? parent.children.push(node) : roots.push(node);
    });
    const keys: (string | number)[] = roots.map(r => r.key);
    treeExpandedKeys.push(...keys);
    return roots;
  }
  function filterTreeWithParents(tree: TreeDataItem[], searchText: string): TreeDataItem[] {
    // 空搜索返回完整树
    if (!searchText.trim()) return tree;

    const lowercaseSearch = searchText.toLowerCase();

    // 递归处理每个节点
    const processNode = (node: TreeDataItem): TreeDataItem | null => {
      // 深拷贝节点避免修改原数据
      const newNode: TreeDataItem = {...node};
      let hasValidChild = false;

      // 处理子节点（后序遍历）
      if (newNode.children?.length) {
        const processedChildren = newNode.children
          .map(child => processNode(child))
          .filter(Boolean) as TreeDataItem[];

        hasValidChild = processedChildren.length > 0;
        newNode.children = processedChildren;
      }

      // 判断当前节点是否匹配
      const isSelfMatch = newNode.title.toLowerCase().includes(lowercaseSearch);

      // 保留条件：自身匹配或包含有效子节点
      return isSelfMatch || hasValidChild ? newNode : null;
    };

    return tree.map(node => processNode(node)).filter(Boolean) as TreeDataItem[];
  }

  return {treeSearchValue,treeData,onTreeExpand, onTreeSelect}
}
